<template>
  <el-card>
    <div slot="header">
      <h3>新增开发需求</h3>
    </div>
    <div>
      <BasicForm
        ref="formData"
        defaultExpandStatus
        formItemWidth="130px"
        :showBtnBar="false"
        :formColumns="formItems"
        :dataSource="formData"
      />
      <skus-table
        ref="skusTable"
        :tableHeight="480"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :actionRender="renderTableBtnAction"
      >
        <!-- 按钮操作栏 -->
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </div>
  </el-card>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import { FORM_ITEMS, TABLE_COLUMNS } from './constants/add';
import { getInitFormData, TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { createExcelByExport, generateUuid, isResponseSuccess } from '@/utils/bizUtils';
import {
  exportTemplateService,
  commitService,
  getDropDownListService
} from '@/api/commodity/developmentRequirementPlan/developRequirementPool';
export default {
  components: {
    BasicForm,
    SkusTable,
    BtnRender
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      btnLoading: {
        export: false,
        submit: false
      }
    }
  },
  created () {
    this.setIndustrySelectOptions()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const exportDevReqBtn = {
        label: '导出开发需求',
        method: this.handleExportDevReq,
        loading: this.btnLoading.export
      }
      const importDevPlanBtn = {
        label: '导入开发需求',
        action: 'sysback/product/devReq/importExcel',
        methods: {
          handleUploadSuccess: this.handleImportDevReq,
          handleBeforeUpload: this.handleBeforeUpload
        },
        data: { devType: this.formData.devType },
        isImport: true,
        loadingFn: this.TableInfo.setLoading
      }
      const submitBtn = {
        label: '提交',
        method: this.handleSubmit,
        disabled: this.TableInfo.isNullList(),
        loading: this.btnLoading.submit
      }
      const clearAllBtn = {
        label: '清空表格数据',
        method: this.handleClearTableData,
        disabled: this.TableInfo.isNullList(),
        type: 'default'
      }
      const gobackBtn = { label: '返回', method: this.handleGoBack, type: 'default' }
      // 按钮通用属性填充
      const btnBars = [gobackBtn, clearAllBtn, exportDevReqBtn, importDevPlanBtn, submitBtn]
      return getListPageBtnsBar(h, btnBars, null)
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row, index }) {
      const actionList = [{ label: '删除', method: () => { this.handleDelete(index) } }]
      return getTableAction({ h, row, actionList })
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'developRequirementPoolList' })
    },
    // 删除
    handleDelete (index) {
      this.TableInfo.removeList(index)
    },
    // 清空表格数据
    handleClearTableData () {
      const content = '确定后将清空所有已导入数据，您确认吗？'
      this.$confirm(content, '清空', {
        type: 'warning',
      }).then(() => {
        this.TableInfo.clearList()
      }).catch(() => {})
    },
    handleBeforeUpload () {
      if (!this.formData.devType) {
        this.$message.warning('请选择开发类型后再导入开发需求！')
        return false
      }
      this.TableInfo.setLoading(true)
    },
    // 导入开发需求
    handleImportDevReq (res) {
      if (isResponseSuccess(res)) {
        this.TableInfo.setList(res.retData)
      }
    },
    // 导出开发需求
    async handleExportDevReq () {
      if (!this.formData.devType) return this.$message.warning('请选择开发类型后再导出！')
      const data = { devType: this.formData.devType }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportTemplateService(data, loadingFn)
      createExcelByExport({ excelTitle: `开发池需求_${generateUuid()}`, res })
    },
    // 提交
    async handleSubmit () {
      const data = {
        detailList: this.TableInfo.list.map(item => ({ ...item, skuParamList: [] })),
        ...this.formData,
        ...this.getIndustryInfoBySubmit()
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await commitService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.handleGoBack()
      }
    },
    // 获取行业表单方法
    useIndustryForm () {
      // 获取行业表单item下标
      const getIndex = () => FORM_ITEMS.findIndex(item => item.prop == 'industryNo')
      // 获取初始后的行业下拉options
      const getOptions = list => (list ?? []).map(item => ({
        value: item.industryNo,
        label: item.industryPath
      }))
      return { getIndex, getOptions }
    },
    // 初始化设置行业下拉options
    async setIndustrySelectOptions () {
      const data = { industryName: '' }
      const res = await getDropDownListService(data)
      if (!res?.retData) return
      const { getIndex, getOptions } = this.useIndustryForm()
      if (getIndex() == -1) return
      this.formItems[getIndex()].options = getOptions(res.retData)
    },
    // 获取提交的行业信息
    getIndustryInfoBySubmit () {
      const { getIndex } = this.useIndustryForm()
      const industryOptions = this.formItems[getIndex()]?.options ?? []
      const info = industryOptions.find(item => item.value == this.formData.industryNo)
      if (info) return _.pick(info, ['industryNo', 'industryPath'])
      // 搜寻不到，新增行业信息
      return { industryNo: '', industryPath: this.formData.industryNo }
    }
  }
}
</script>
